package com.ww.aiinterviewer.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ww.aiinterviewer.common.ErrorCode;
import com.ww.aiinterviewer.constant.CommonConstant;
import com.ww.aiinterviewer.exception.BusinessException;
import com.ww.aiinterviewer.exception.ThrowUtils;
import com.ww.aiinterviewer.mapper.ChatRoomMapper;
import com.ww.aiinterviewer.model.dto.chatroom.ChatRoomQueryRequest;
import com.ww.aiinterviewer.model.entity.ChatRoom;
import com.ww.aiinterviewer.model.entity.User;
import com.ww.aiinterviewer.model.vo.ChatRoomVO;
import com.ww.aiinterviewer.model.vo.UserVO;
import com.ww.aiinterviewer.service.ChatRoomService;
import com.ww.aiinterviewer.service.UserService;
import com.ww.aiinterviewer.utlis.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 聊天房间服务实现
 *
 * @author 15357
 */
@Service
@Slf4j
public class ChatRoomServiceImpl extends ServiceImpl<ChatRoomMapper, ChatRoom> implements ChatRoomService {

    @Resource
    private UserService userService;
    
    @Override
    public void validChatRoom(ChatRoom chatRoom, boolean add) {
        if (chatRoom == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = chatRoom.getTitle();
//        String messages = chatRoom.getMessages();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
//        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
//        }
    }

    /**
     * 获取查询包装类
     *
     * @param chatRoomQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<ChatRoom> getQueryWrapper(ChatRoomQueryRequest chatRoomQueryRequest) {
        QueryWrapper<ChatRoom> queryWrapper = new QueryWrapper<>();
        if (chatRoomQueryRequest == null) {
            return queryWrapper;
        }
        String searchText = chatRoomQueryRequest.getSearchText();
        String sortField = chatRoomQueryRequest.getSortField();
        String sortOrder = chatRoomQueryRequest.getSortOrder();
        Long id = chatRoomQueryRequest.getId();
        String title = chatRoomQueryRequest.getTitle();
        Long userId = chatRoomQueryRequest.getUserId();
        Long notId = chatRoomQueryRequest.getNotId();
        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }
    

    @Override
    public ChatRoomVO getChatRoomVO(ChatRoom chatRoom) {
        ChatRoomVO chatRoomVO = ChatRoomVO.objToVo(chatRoom);
        // 1. 关联查询用户信息
        Long userId = chatRoom.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        chatRoomVO.setUser(userVO);
        return chatRoomVO;
    }

    @Override
    public Page<ChatRoomVO> getChatRoomVOPage(Page<ChatRoom> chatRoomPage, HttpServletRequest request) {
        List<ChatRoom> chatRoomList = chatRoomPage.getRecords();
        Page<ChatRoomVO> chatRoomVOPage = new Page<>(chatRoomPage.getCurrent(), chatRoomPage.getSize(), chatRoomPage.getTotal());
        if (CollUtil.isEmpty(chatRoomList)) {
            return chatRoomVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = chatRoomList.stream().map(ChatRoom::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<ChatRoomVO> chatRoomVOList = chatRoomList.stream().map(chatRoom -> {
            ChatRoomVO chatRoomVO = ChatRoomVO.objToVo(chatRoom);
            Long userId = chatRoom.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            chatRoomVO.setUser(userService.getUserVO(user));
            return chatRoomVO;
        }).collect(Collectors.toList());
        chatRoomVOPage.setRecords(chatRoomVOList);
        return chatRoomVOPage;
    }

    @Override
    public List<ChatRoomVO> getChatRoomVOList(HttpServletRequest request) {
        // 当前登录用户
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            return new ArrayList<ChatRoomVO>();
        }
        List<ChatRoom> chatRoomList = this.list(new QueryWrapper<ChatRoom>().eq("userId", loginUser.getId()));
        // 填充信息
        List<ChatRoomVO> chatRoomVOList = chatRoomList.stream().map(chatRoom -> {
            ChatRoomVO chatRoomVO = ChatRoomVO.objToVo(chatRoom);
            chatRoomVO.setUser(userService.getUserVO(loginUser));
            chatRoomVO.setMessageList(new ArrayList<>());
            return chatRoomVO;
        }).collect(Collectors.toList());
        return chatRoomVOList;
    }
}




